package com.atstudying.mall.product.exception;

import com.atstudying.common.exception.BigCodeEnume;
import com.atstudying.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Mr.zhneg
 * @create 2020-10-14-10:53
 * 集中处理所有异常
 */
//集中的异常处理器类
@Slf4j
//所有的json数据都要以json的方式返回给前端
//@ResponseBody
//@ControllerAdvice(basePackages = "com.atstudying.mall.product.controller")
@RestControllerAdvice(basePackages = "com.atstudying.mall.product.controller")
public class MallExceptionController {


    //它告诉springmvc，它可以处理什么异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){

        log.error("数据校验出现问题：{}，异常类型：{}",e.getMessage(),e.getClass());
        BindingResult result=e.getBindingResult();

        Map<String,String> error=new HashMap<>();
        result.getFieldErrors().forEach((fieldError -> {
            error.put(fieldError.getField(),fieldError.getDefaultMessage());
        }));
        return R.error(BigCodeEnume.VALID_EXCEPTION.getCode(),BigCodeEnume.VALID_EXCEPTION.getMsg()).put("data",error);
    }

    //对于异常处理，统一用这个感知
    @ExceptionHandler(value = Throwable.class)
    public R handleValidException(Throwable e){

        log.error("数据校验出现问题：{}，异常类型：{}",e.getMessage(),e.getClass());

        return R.error(BigCodeEnume.UNKNOW_EXCEPTION.getCode(),BigCodeEnume.UNKNOW_EXCEPTION.getMsg()).put("data",e.getMessage());
    }
}
